<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */


    public function reset(Request $request)
    {
        $validate=Validator::make($request->all(),[
            'old_password'=>'required|min:1',
            'new_password'=>'required|min:1'
        ]);

        if($validate->fails())
        {
            return $this->fail(400006,$validate->errors());
        }

        $id=JWTAuth::parseToken()->authenticate()->id;

        $old_password=$request->get('old_password');
        $real_old_password=User::where('id',$id)->select('password')->get()[0]->password;

        if(!Hash::check($old_password,$real_old_password))
        {
            $tag=new \stdClass();
            $tag->old_password=['原密码不正确'];
            return $this->fail(400006,$tag);
        }

        User::where('id',$id)->update([
            'password'=>bcrypt($request->get('new_password'))
        ]);

        JWTAuth::setToken(JWTAuth::getToken())->invalidate();

        return $this->success();
    }

}
